<template>
  <div>
    <h1>个人中心</h1>
    <div v-if="accountInfoData">
      <div class="item">
      <div class="text">
        管理员ID:
      </div>
      <div class="value">
        {{ accountInfoData.id }}
      </div>
    </div>
    <div class="item">
      <div class="text">
        账号:
      </div>
      <div class="value">
        {{ accountInfoData.account }}
      </div>
    </div>
    <div class="item">
      <div class="text">
        用户组:
      </div>
      <div class="value">
        {{ accountInfoData.userGroup }}
      </div>
    </div>
    <div class="item">
      <div class="text">
        创建时间:
      </div>
      <div class="value">
        {{ accountInfoData.ctime }}
      </div>
    </div>

    <div class="avatar">
      管理员头像:
    </div>
      <el-upload
      class="avatar-uploader"
      :action="serverUrl+'/users/avatar_upload?id='+accountInfoData.id"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
    <img v-if="accountInfoData.imgUrl" :src="serverUrl+accountInfoData.imgUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
    </div>
</template>

<script setup>
import {accountInfo} from '@/api/account'
import {ref} from 'vue'
import {serverUrl} from '@/utils/common'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {userStore} from '@/stores/userStore'

const accountInfoData = ref(null);
const store = userStore()

const getAccountInfo = async () => {
  let {id} = JSON.parse(sessionStorage.getItem('user'));
  const res = await accountInfo({id});
  accountInfoData.value = res.accountInfo
}
getAccountInfo()


//上传之前 判断 检测用户上传的文件是否合法 
// 合法 true 
// 不合法  false  并 提示用户文件的问题
const beforeAvatarUpload = (file) => {
    console.log(file);
    // 判断文件类型必须是 图片
    if(!file.type.includes('image')){
      ElMessage.error('文件类型必须是图片');
      return false;
    }
    if(file.size >1*1024*1024){
      ElMessage.error('文件大小不能超过 1M');
      return false;
    }
  return true ;  
}

// 修改用户头像成功后 
// 重新获取用户的信息

const handleAvatarSuccess = () => {
  // router.go(0)
  getAccountInfo()
  // 修改poinia中状态 表示我已经修改了头像
  store.changeUserInfoState()
}

</script>

<style scoped lang="scss">
.item {
  width: 100%;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #ccc;
  display: flex;
}

.avatar {
  width: 100%;
  height: 50px;
  line-height: 50px;
}
.avatar_img{
  width: 200px;
  height: 200px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #409eff;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  
}


.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>